<html>
<head>
    <meta charset="UTF-8">
    <title>SSE测试页面</title>
</head>
<body>
<h1>SSE测试页面</h1>
<label for="clientId">Client Id:</label><input type="text" value="123" id="clientId">
<button onclick="sseConnect()">连接</button>
<button id="disconnectButton">断开连接</button>
<div id="msgElement"></div>
</body>
<script>
    function sseConnect() {
        const clientIdElement = document.getElementById('clientId');
        const clientIdValue = clientIdElement.value; // 获取input元素的值
        const source = new EventSource('/sse/connect/' + clientIdValue);
        source.onmessage = function (event) {
            const msgElement = document.getElementById('msgElement');
            let text = msgElement.innerText;
            text += event.data + '\n';
            msgElement.innerText = text;
        }
        source.onopen = function (event) {
            const msgElement = document.getElementById('msgElement');
            const text = '连接已建立\n';
            msgElement.innerText = text;
        }

        function disconnectSSE() {
            if (source.readyState === EventSource.OPEN) {
                source.close(); // 关闭连接
                console.log("SSE连接已断开");
            } else {
                console.log("SSE连接已关闭或未建立");
            }
        }

        const disconnectButton = document.getElementById('disconnectButton');
        // 添加点击事件监听器
        disconnectButton.addEventListener('click', function() {
            disconnectSSE(); // 调用断开连接的函数
        });
    }

</script>
</html>